const router = require("koa-router")();
const loginCheck = require("../middlewares/logincheck.js");
const {
  handleCreateNote,
  handleCommentListAll,
  handleCommentListOne,
  handleDeleteList,
  handleUpdateList,
} = require("../controller/CommnetController.js");

router.prefix("/comment");

router.post("/create", loginCheck, async (ctx, next) => {
  const { content } = ctx.request.body;
  const { username } = ctx.session.userInfo;
  const createNoteRes = await handleCreateNote({
    username,
    content,
  });
  if (createNoteRes) {
    ctx.body = {
      errno: 0,
      message: "success",
      data: createNoteRes,
    };
  } else {
    ctx.body = {
      errno: -1,
      message: "留言失败",
    };
  }
});

//获取留言数据 filterType =1 看全部 =2 看自己
router.get("/list", loginCheck, async (ctx, next) => {
  let { filterType } = ctx.query;
  filterType = parseInt(filterType) || 1;
  let res;
  if (filterType === 1) {
    res = (await handleCommentListAll()) || null;
  } else if (filterType === 2) {
    res = (await handleCommentListOne(ctx.session.userInfo.username)) || null;
  }
  if (res) {
    ctx.body = {
      errno: 0,
      data: res,
    };
  } else {
    ctx.body = {
      errno: -1,
      data: "note not found",
    };
  }
});

//删除留言
router.post("/del", loginCheck, async (ctx, next) => {
  const { username } = ctx.session.userInfo;
  const { _id } = ctx.request.body;
  try {
    await handleDeleteList(username, _id);
  } catch (error) {
    console.error(error);
  }
});

//更新留言
router.post("/update", loginCheck, async (ctx, next) => {
  const { username } = ctx.session.userInfo;
  const { _id, content } = ctx.request.body;
  try {
    const newData = await handleUpdateList(_id, username, content);
    ctx.body = {
      errno: 0,
      data: newData,
    };
  } catch (error) {
    console.error(error);
    ctx.body = {
      errno: -1,
      message: "更新失败",
    };
  }
});

module.exports = router;
